package common.util;

import java.util.Hashtable;
import java.util.Map;

public class CachedMap {
	private static Map<Object, Map<Object, Object>> MAP = new Hashtable<Object, Map<Object, Object>>();

	public static Object NULL_VALUE = new Object();

	public static Map<Object, Object> NULL_MAP = new Hashtable<Object, Object>();

	private CachedMap() {
	}

	public static void addValue(Object cKey1, Object cKey2, Object cValue) {
		Map<Object, Object> tMap = getMap(cKey1);
		tMap.put(cKey2, cValue);
	}

	public static void addNull(Object cKey1) {
		MAP.put(cKey1, NULL_MAP);
	}

	public static void addNull(Object cKey1, Object cKey2) {
		Map<Object, Object> tMap = getMap(cKey1);
		tMap.put(cKey2, NULL_VALUE);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getValue(Object cKey1, Object cKey2) {
		Map<Object, Object> tMap = getMap(cKey1);
		if (tMap == NULL_MAP) {
			return null;
		}
		Object tObject = tMap.get(cKey2);
		if (tObject == null || tObject == NULL_VALUE) {
			return null;
		} else {
			return (T) tObject;
		}
	}

	@SuppressWarnings("unchecked")
	public static <K, Y> Map<K, Y> getMap(Object cKey1) {
		Map<Object, Object> tMap = MAP.get(cKey1);
		if (tMap == null) {
			tMap = new Hashtable<Object, Object>();
			MAP.put(cKey1, tMap);
		}
		return (Map<K, Y>) tMap;
	}

	public static void refresh() {
		MAP.clear();
	}

	public static void refresh(Object cKey1) {
		Map<Object, Object> tMap = getMap(cKey1);
		if (tMap != null) {
			tMap.clear();
		} else if (tMap == NULL_MAP) {
			MAP.put(cKey1, null);
		}
	}
}
